//
//  HLUserAccount.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/15.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLUserAccount.h"

@implementation HLUserAccount

+ (instancetype)userAccountWithDictionary:(NSDictionary *)dic {
    //创建对象
    HLUserAccount *userAccount = [[HLUserAccount alloc] init];
    //赋值
    [userAccount setValuesForKeysWithDictionary:dic];
    return userAccount;
}
//重写,抛出没找到的key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}

//重写set方法给过期时间赋值
- (void)setExpires_in:(double)expires_in {
    _expires_in = expires_in;
    //获取过期时间
    _expires_date = [NSDate dateWithTimeIntervalSinceNow:expires_in];
}
//保存
- (void)saveUserAccountToSanbox {
    //获取沙盒路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"userAccount.plist"];
    //对对象进行归档
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}
//取出
+ (instancetype)getUserAccount {
    //获取沙盒路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"userAccount.plist"];
    //取出对象
    HLUserAccount *userAccount = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    //判断用户的数据是否过期
    if ([userAccount.expires_date compare:[NSDate date]] == NSOrderedDescending) {
        //没有过期才返回
        return userAccount;
    }
    return nil;
}

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeDouble:self.expires_in forKey:@"expires_in"];
    [aCoder encodeObject:self.uid forKey:@"uid"];
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.avatar_large forKey:@"avatar_large"];
    [aCoder encodeObject:self.expires_date forKey:@"expires_date"];
}

//解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        _access_token = [aDecoder decodeObjectForKey:@"access_token"];
        _expires_in = [aDecoder decodeDoubleForKey:@"expires_in"];
        _uid = [aDecoder decodeObjectForKey:@"uid"];
        _name = [aDecoder decodeObjectForKey:@"name"];
        _avatar_large = [aDecoder decodeObjectForKey:@"avatar_large"];
        _expires_date = [aDecoder decodeObjectForKey:@"expires_date"];
    }
    return self;
}

@end
